package com.cl.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Xml;

/**
 * 短信的备份和还原 工具类
 */
public class SmsUtils {
	/**
	 * 短信备份
	 * @param context
	 * @throws IllegalArgumentException
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public interface ProgressCallBack {
		/**
		 * 开始备份或返原的时候，设置进度的最大值
		 * @param max 最大值
		 */
		public void onBefore(int max);
		/**
		 * 备份或返原过程中，增加进度
		 * @param progress  当前进度
		 */
		public void onOperation(int progress);
	}
	public static void backupSms(Context context, ProgressCallBack callback) throws IllegalArgumentException, IllegalStateException, IOException {
		ContentResolver resolver = context.getContentResolver();
		Uri uri = Uri.parse("content://sms/");
		XmlSerializer seria = Xml.newSerializer();
		File file = new File(Environment.getExternalStorageDirectory(),"backupsms.xml");
		FileOutputStream os = new FileOutputStream(file);
		seria.setOutput(os, "utf-8");
		seria.startDocument("utf-8",true);//true 是否独立
		seria.startTag(null,"smss");
		Cursor cursor = resolver.query(uri, new String[]{"date","address","type","body"}, null, null, null);
		int max = cursor.getCount();
		int progress = 0;
		callback.onBefore(max);
		seria.attribute(null, "max", max + "");
		while(cursor.moveToNext()) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String date = cursor.getString(0);
			String address = cursor.getString(1);
			String type = cursor.getString(2);
			String body = cursor.getString(3);
			seria.startTag(null,"sms");
			seria.startTag(null,"date");
			seria.text(date);
			seria.endTag(null, "date");
			
			seria.startTag(null,"address");
			seria.text(address);
			seria.endTag(null, "address");
			
			seria.startTag(null,"type");
			seria.text(type);
			seria.endTag(null, "type");
			
			seria.startTag(null,"body");
			seria.text(body);
			seria.endTag(null, "body");
			
			seria.endTag(null, "sms");
			progress ++;
			callback.onOperation(progress);
		}
		seria.endTag(null, "smss");
		seria.endDocument();
		os.close();
		cursor.close();
	}
	
	/**
	 * 还原短信
	 * 
	 * @param context
	 * @param flag
	 *            是否清理原来的短信
	 * @throws XmlPullParserException 
	 * @throws FileNotFoundException 
	 */
	public static void restoreSms(Context context, boolean flag, ProgressCallBack callback) throws Exception {
		Uri uri = Uri.parse("content://sms/");
		if (flag) {//true则清除本身的短信
			context.getContentResolver().delete(uri, null, null);
		}
		// 1.读取sd卡上的xml文件
		// Xml.newPullParser();
		XmlPullParser pull = Xml.newPullParser();
		File file = new File(Environment.getExternalStorageDirectory(),"backupsms.xml");
		FileInputStream fis = new FileInputStream(file);
		pull.setInput(fis,"utf-8");
		int eventType = pull.getEventType();
		String body = null;
		String date = null;
		String type = null;
		String address = null;
		ContentValues values = null;
		//当前进度
		int progress = 0;
		while(eventType != XmlPullParser.END_DOCUMENT){
			String tagName = pull.getName();
			
			switch (eventType) {
				case XmlPullParser.START_TAG: //如果是开始标签
					if("smss".equals(tagName)) {
						// 2.读取max
						String max = pull.getAttributeValue(null, "max");
						callback.onBefore(Integer.parseInt(max));
						
					}
					// 3.读取每一条短信信息，body date type address
					if("body".equals(tagName)){
						body = pull.nextText();
					}else if("date".equals(tagName)){
						date = pull.nextText();
					}else if("type".equals(tagName)){
						type = pull.nextText();
					}else if("address".equals(tagName)){
						address = pull.nextText();
					}
					break;
				case XmlPullParser.END_TAG:
					// 4.把短信插入到系统短息应用。
					//模拟多条短信的还原的耗时操作
					Thread.sleep(500);
					
					if("sms".equals(tagName)){
						values = new ContentValues();
						values.put("body",body);
						values.put("date",date);
						values.put("type",type);
						values.put("address",address);
						context.getContentResolver().insert(uri, values);
						progress ++;
						callback.onOperation(progress);
					}
					break;
			}
			eventType = pull.next();
		}
		fis.close();

//		ContentValues values2 = new ContentValues();
//		values2.put("body", "woshi duanxin de neirong");
//		values2.put("date", "1395045035573");
//		values2.put("type", "1");
//		values2.put("address", "5558");
//		context.getContentResolver().insert(uri, values2);
	}
}
